import { _decorator, Component, Node, instantiate, Prefab, Label, tween, Vec3 } from 'cc';
import Instance from '../utils/Instance';
const { ccclass, property } = _decorator;

@ccclass('UIMgr')
export class UIMgr extends Component {
    public static getInstance(): UIMgr {
        return Instance.get<UIMgr>(UIMgr);
    }

    // UI 根节点
    @property(Node)
    private uiRoot: Node = null;

    // 弹窗预制体
    @property(Prefab)
    private popupPrefab: Prefab = null;

    // 提示预制体
    @property(Prefab)
    private toastPrefab: Prefab = null;

    onLoad() {}

    // 显示弹窗
    public showPopup(title: string, content: string, callback?: Function): void {
        if (!this.popupPrefab) return;

        // 实例化弹窗
        const popupNode = instantiate(this.popupPrefab);
        this.uiRoot.addChild(popupNode);

        // 设置弹窗内容
        const titleLabel = popupNode.getChildByName('Title').getComponent(Label);
        const contentLabel = popupNode.getChildByName('Content').getComponent(Label);
        if (titleLabel) titleLabel.string = title;
        if (contentLabel) contentLabel.string = content;

        // 绑定关闭按钮事件
        const closeButton = popupNode.getChildByName('CloseButton');
        if (closeButton) {
            closeButton.on('click', () => {
                this.hidePopup(popupNode);
                if (callback) callback();
            });
        }
    }

    // 隐藏弹窗
    public hidePopup(popupNode: Node): void {
        if (popupNode) {
            popupNode.removeFromParent();
            popupNode.destroy();
        }
    }

    // 显示提示
    public showToast(message: string, duration: number = 2): void {
        if (!this.toastPrefab) return;

        // 实例化提示
        const toastNode = instantiate(this.toastPrefab);
        this.uiRoot.addChild(toastNode);

        // 设置提示内容
        const messageLabel = toastNode.getChildByName('Message').getComponent(Label);
        if (messageLabel) messageLabel.string = message;

        // 提示动画
        toastNode.setPosition(new Vec3(0, -200, 0)); // 初始位置
        tween(toastNode)
            .to(0.3, { position: new Vec3(0, 0, 0) }) // 向上移动
            .delay(duration) // 停留时间
            .to(0.3, { position: new Vec3(0, -200, 0) }) // 向下移动
            .call(() => {
                toastNode.removeFromParent();
                toastNode.destroy();
            })
            .start();
    }
}
